let that = null
class Tab {
    constructor(id) {
        // 获取元素
        that = this
        this.main = document.querySelector(id)
        this.add = this.main.querySelector('.tabadd')
        this.ul = this.main.querySelector('.firstnav ul:first-child')
        this.fsection = this.main.querySelector('.tabscon')
        this.init()
    }
    init() {
        this.lis = this.main.querySelectorAll('li')
        this.sections = this.main.querySelectorAll('section')
        this.remove = this.main.querySelectorAll('.icon-guanbi')
        this.spans = this.main.querySelectorAll('.firstnav li span:first-child')

        this.add.onclick = this.addTab
        // init 初始化操作让相关的元素绑定事件
        for (let i = 0; i < this.lis.length; i++) {
            this.lis[i].index = i
            this.lis[i].onclick = this.toggleTab
            this.remove[i].onclick = this.removeTab
            this.spans[i].ondblclick = this.editTab
            this.sections[i].ondblclick = this.editTab
        }
    }
    // 1. 切换功能
    toggleTab() {
        // console.log(this.index)
        that.clearClass()
        this.className = 'liactive'
        that.sections[this.index].className = 'conactive'
    }
    clearClass() {
        for (let i = 0; i < this.lis.length; i++) {
            this.lis[i].className = ''
            this.sections[i].className = ''
        }
    }
    // 2. 添加功能
    addTab() {
        that.clearClass()
        // 创建li元素和section元素
        const li = `<li class=liactive><span>新选项卡</span><span class="iconfont icon-guanbi"></span></li>`
        const section = `<section class="conactive">测试${Math.random()}</section>`
        // 把这两个元素追加到对应的父元素后面
        that.ul.insertAdjacentHTML('beforeend', li)
        that.fsection.insertAdjacentHTML('beforeend', section)
        that.init()
    }
    // 3. 删除功能
    removeTab(e) {
        e.stopPropagation()
        let index = this.parentNode.index
        that.lis[index].remove()
        that.sections[index].remove()
        that.init()
        // 查询是否还有选中状态的, 如果有就说明删除的不是选中的, 不用选中上一项
        if (document.querySelector('.liactive')) return
        // 如果删除了选中, 就默认选中上一项
        that.lis[-- index] && that.lis[index].click()
    }
    // 4. 修改功能
    editTab() {
        let str = this.innerHTML
        // 双击禁止选中文字
        window.getSelection() ? window.getSelection().removeAllRanges() : document.getSelection().empty()
        this.innerHTML = `<input type='text' value="${str}"/>`
        let input = this.children[0]
        input.select() // 文本框里面的文字处于选定状态
        // 当我们离开文本框就把文本框里面的值给span
        input.onblur = function () {
            this.parentNode.innerHTML = this.value
        }
        // 按下enter确认输入
        input.onkeyup = function (e) {
            if (e.key === 'Enter') {
                this.blur()
            }
        }
    }
}

new Tab('#tab')